/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package sharefileclient;

import sharefileinterface.FilePart;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.MalformedURLException;
import java.rmi.Naming;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.JProgressBar;
import sharefileinterface.ClientInterface;

/**
 *
 * @author anwedo
 */
public class DownloadThread extends Thread {

    final public static long PART_SIZE = 1000000;

    private final ClientGUI mainThread;

    private final int fid;
    private final String ipadd;
    private final String fileGet;
    private JProgressBar progress;
    private final long size;
    private final long partTotal;
    public sharefileinterface.ShareFileInterface server;
    public LinkedHashMap<Integer, ArrayList<FilePart>> fileShareList;

    public DownloadThread(ClientGUI mainThread, String ipadd, int fid, String fileGet, long size, JProgressBar progress) {
        this.mainThread = mainThread;
        this.fid = fid;
        this.ipadd = ipadd;
        this.fileGet = fileGet;
        this.progress = progress;
        this.size = size;
        this.partTotal = this.size / PART_SIZE + 1;
    }

    @Override
    public void run() {
        FileOutputStream fos;
        try {
            progress.setMinimum(0);
            progress.setMaximum(100);

            server = mainThread.server;
            ClientInterface c;
            LinkedHashMap<String, Integer> listAddressPart;
            int hasTotalPart;
            while (true) {
                //get client has file
                try{
                    listAddressPart = server.needFilePart(mainThread.getmacAdd(), fid);
                }catch(RemoteException ex){
                    //server die
                    Logger.getLogger(DownloadThread.class.getName()).log(Level.SEVERE, null, ex);
                    listAddressPart = new LinkedHashMap<>();
                }
                //get partList
                fileShareList = mainThread.fileShareList;
                ArrayList<FilePart> filePartList = fileShareList.get(new Integer(fid));
                if (filePartList == null) {
                    filePartList = new ArrayList<>();
                    //put to fileshare
                    fileShareList.put(new Integer(fid), filePartList);
                }
                hasTotalPart = mainThread.hasRealPart(filePartList);
                //Thong bao den server
                //mainThread.server.hasFilePart(mainThread.getmacAdd(), fid, hasTotalPart);
                for (String address : listAddressPart.keySet()) {
                    Integer hasPart = listAddressPart.get(address);
                    if (hasTotalPart < hasPart.intValue()) {
                        //Ket noi den client chia se file
                        c = (ClientInterface) Naming.lookup("rmi://" + ipadd + ":2013" + "/ShareServerOnClient");
                        System.out.println("Ket noi den client chia se thanh cong");
                        //Yeu cau phan file
                        for (int i = hasTotalPart; i < hasPart.intValue(); i++) {
                            FilePart partSave = c.needFilePart(fid, i);
                            //add
                            filePartList.add(partSave);
                            hasTotalPart = mainThread.hasRealPart(filePartList);
                            //Thong bao den server
                            mainThread.server.hasFilePart(mainThread.getmacAdd(), fid, hasTotalPart);
                            float p = hasTotalPart;
                            int per = (int)(p/this.partTotal * 100);
                            progress.setValue(per);
                            try {
                                sleep(2000);
                            } catch (InterruptedException ex) {
                                Logger.getLogger(DownloadThread.class.getName()).log(Level.SEVERE, null, ex);
                            }
                        }
                    }
                }

                //check has all part
                if (hasTotalPart >= this.partTotal) {
                    try {
                        //ghi vao file
                        System.out.println("File to Save: " + fileGet);
                        String currentDirectory = System.getProperty("user.dir");
                        String uploaddirectory = currentDirectory + "\\share\\" + fileGet + ".tmp";
                        File of = new File(uploaddirectory);
                        fos = new FileOutputStream(of);

                        for (FilePart part : filePartList) {
                            fos.write(part.data, 0, part.data.length);
                        }
                        fos.close();
                        progress.setValue(0);
                        System.out.println("Download completed!");
                        JOptionPane.showMessageDialog(mainThread.getRootPane(), "Download completed!");
                        //rename file
                        File nf = new File(uploaddirectory);
                        if (!nf.exists()) {
                            of.renameTo(nf);
                        }
                    } catch (IOException ex) {
                        Logger.getLogger(DownloadThread.class.getName()).log(Level.SEVERE, null, ex);
                    }
                    break;
                }
            }
        } catch (MalformedURLException | NotBoundException | RemoteException ex) {
            Logger.getLogger(DownloadThread.class.getName()).log(Level.SEVERE, null, ex);
        }

    }
}
